import axios from 'axios';
import JSZip from 'jszip';
import FileSaver from 'file-saver';

class DownLoader {
  //基本配置
  constructor() {
    this.Axios = axios.create();
    this.error = [];
    this.folderName = '模型文件';
  }

  // const data ={
  //   "name":"",
  //   "path":[],
  //   "url":""
  // }

  /*
  1.下载失败
  2.部分文件下载失败
  */

  download(data) {
    const zip = new JSZip();
    const cache = {};
    const promises = [];

    data.forEach((item) => {
      const promise = this.getFile(item.url).then((data) => {
        zip.folder(item.path.join('/')).file(item.name, data, { binary: true }); // 逐个添加文件
        cache[item.name] = data;
      });
      promises.push(promise);
    });

    return new Promise((resolve, reject) => {
      Promise.all(promises)
        .then(() => {
          console.log('resolve');
          zip.generateAsync({ type: 'blob' }).then((content) => {
            // 生成二进制流
            FileSaver.saveAs(content, this.folderName); // 利用file-saver保存文件
            resolve();
          });
        })
        .catch((e) => {
          console.log('reject', e);
          reject();
        });
    });
  }

  //文件夹名称
  setFolderName(name) {
    this.folderName = name;
  }

  // 把路径指向文件转成ArrayBuffer对象
  getFile(url) {
    return new Promise((resolve, reject) => {
      this.Axios({
        method: 'get',
        url,
        responseType: 'arraybuffer',
      })
        .then((data) => {
          resolve(data.data);
        })
        .catch((error) => {
          console.log(error);
          reject(error.toString());
        });
    });
  }
}

export default DownLoader;
